﻿using Microsoft.SharePoint.ApplicationPages;
using System.Text;
using System.IO;
using System.Globalization;
using System.IdentityModel.Tokens;
using Microsoft.IdentityModel.Claims;
using System;
using Microsoft.IdentityModel.Web;
using System.Web;
using Microsoft.IdentityModel.Protocols.WSFederation;
using Microsoft.SharePoint.Utilities;
using System.Configuration;

namespace Veracruz.Facebook.Sharepoint.FeatureActions
{
    public partial class FacebookAuth 
        :GlobalAdminPageBase
        //: WebAdminPageBase
    {
        public const string CachedClaims = "CachedClaims";
        //public const string RedirectionTarget = "applications.aspx";

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ProcessRequest();
        }

        protected override void OnLoad(System.EventArgs e)
        {
            
            //ProcessRequest();
            base.OnLoad(e);
        }

        public void ProcessRequest()
        {
            FederatedAuthenticationModule l_federatedAuthenticationModule = FederatedAuthenticationModule.Current;

            if (l_federatedAuthenticationModule == null)
            {
                throw new ConfigurationErrorsException("FederatedAuthenticationModule not found.");
            }
            
            //HACK: No session available by default so don't forget to activate it 
            //in web.config (module Session and EnableSessionState = true)
            if(this.Context.Session[CachedClaims] == null)
            {
                if (!l_federatedAuthenticationModule.IsPassiveSignInResponse(this.Context.Request))
                {
                    // User is trying to get to the page w/o being authenticated
                    // We are going to redirect him to our STS. The address is stored in FAM.Issuer property
                    l_federatedAuthenticationModule.RedirectToIdentityProvider(this.Context);
                }
                else
                {
                    // Get the xml token from the form post
                    string l_tokenXml = l_federatedAuthenticationModule.GetXmlTokenFromPassiveSignInResponse(this.Context.Request, null);

                    if (String.IsNullOrEmpty(l_tokenXml))
                    {
                        throw new InvalidOperationException("Cannot parse the returned security token");
                    }

                    // Validate the token
                    SecurityToken token = null;
                    IClaimsPrincipal l_principal = l_federatedAuthenticationModule.AuthenticateUser(l_tokenXml, out token);

                    //HACK: No session available by default so don't forget to activate it 
                    //in web.config (module Session and EnableSessionState = true)
                     this.Context.Session[CachedClaims] = l_principal;

                    //_admin/applications.aspx
                    //SPUtility.Redirect("applications.aspx", SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
                     //SPUtility.Redirect("/_admin/applications.aspx", SPRedirectFlags.Static, this.Context);
                     RedirectToApplicationManagementPage();
                }
            }
        }

        private static string GetPathAndQuery(WSFederationMessage request)
        {
            StringBuilder l_strb = new StringBuilder(128);
            using (StringWriter writer = new StringWriter(l_strb, CultureInfo.InvariantCulture))
            {
                request.Write(writer);
                return l_strb.ToString();
            }
        }
    }
}
